// @version go-erp 0.1
// @author xiaotangren  <unphp@qq.com>
// @data 2014-11-13
// route
package api

import (
	"fmt"
	"runtime/debug"
)

//路由接口
type ControllerInterface interface {
	Route(action string, b []byte) (code int, rsData string)
}

//路由
type ApiRoute struct {
	ControllerMap map[string]func() ControllerInterface
}

//添加“控制器”路由
func (r *ApiRoute) AddRouterController(name string, c func() ControllerInterface) {
	if r.ControllerMap == nil {
		r.ControllerMap = make(map[string]func() ControllerInterface, 0)
	}
	r.ControllerMap[name] = c
}

//路由分发
func (r *ApiRoute) Route(controller, action string, b []byte) (code int, rsData string) {
	defer func() {
		if err := recover(); err != nil {
			code = 0
			rsData = fmt.Sprint(err)
			fmt.Println(err)
			debug.PrintStack()
			return
		}
	}()
	var c ControllerInterface

	if a, ok := r.ControllerMap[controller]; ok {
		c = a()
	} else {
		code = 0
		rsData = "Error::not this api's controller![" + controller + "]"
		return
	}
	code, rsData = c.Route(action, b)
	return
}
